package com.lushuan.ch11_springboot_test.demo.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ch4_java 线程池拒绝策略触发条件演示
 */
public class ThreadPoolRejectedExecutionHandlerDemo {

    public static void main(String[] args) {
        // 创建线程池，核心线程数2，最大线程数4，队列容量2
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 4, 10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()  // 设置拒绝策略
        );

        // 提交6个任务
        for (int i = 1; i <= 6; i++) {
            final int taskID = i;
            executor.submit(() -> {
                System.out.println("Executing task " + taskID + " by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);  // 模拟任务执行
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        executor.shutdown();
    }

}
